/*
 * @Descripttion: 延时处理
 * @version: 
 * @Author: chenbolin@msn.cn
 * @Date: 2021-06-04 17:20:58
 * @LastEditors:  
 * @LastEditTime: 2022-10-31 10:18:38
 */
#include "SysDelayProcess.h"
#include "Sys.h"

#define SYS_DELAY_PROCESS_NUM 3

typedef struct 
{
    bool enable;
    uint32_t processTime;
    SysDelayProcessHandle_cb handle;
    void *args;
}DelayProcess_t;

static DelayProcess_t g_delayProcess[SYS_DELAY_PROCESS_NUM];
/**
 * @name: 延时处理注册
 * @msg: 
 * @param {uint32_t} delay，延时时间（毫秒）
 * @param {SysDelayProcessHandle_cb} handle，处理函数
 * @param {void} *args，传递给handle的参数
 * @return {0=成功，-1=失败}
 */
int SysDelayProcessRegist(uint32_t delay, SysDelayProcessHandle_cb handle, void *args)
{
    uint8_t i;
    DelayProcess_t *dp;
    
    if(handle)
    {
        for(i = 0; i < SYS_DELAY_PROCESS_NUM; i++)
        {
            dp = &g_delayProcess[i];
            if(!dp->enable)
            {
                dp->enable = true;
                dp->handle = handle;
                dp->args   = args;
                dp->processTime = SysTime() + delay;
                return 0;
            }
        }
    }
    return -1;
}

void SysDelayProcessInit(void)
{
    uint8_t i;
    for(i = 0; i < SYS_DELAY_PROCESS_NUM; i++)
    {
        g_delayProcess[i].enable = false;
    }
}

void SysDelayProcessPoll(void)
{
    uint8_t i;
    DelayProcess_t *dp;

    for(i = 0; i < SYS_DELAY_PROCESS_NUM; i++)
    {
        dp = &g_delayProcess[i];
        if(dp->enable && SysTime() >= dp->processTime)
        {
            dp->handle(dp->args);
            dp->enable = false;
        }
    }
}

